#! /bin/sh

# select a path to save the log file
log_file="/root/usbhd_test.log"

# select a mount point
mount_point="/root/sdx"

# create a big.bin first, and then cp this file to $cp_to,
# next check $cp_from and $cp_to is as same or not.
checksum="sha1sum.txt"
cp_from="big.bin"
cp_to="test.bin"

# add 'date' informations to every line
last_is_newline=1
function write_log()
{
	if [ $last_is_newline -eq 1 ]; then
		date >> $log_file
	fi

	until [ -z "$1" ]; do
		echo -e -n "$1"
		echo -e -n "\t $1" | tr '\b' ' ' >> $log_file

		# check if the last line is a newline
		# another best way, but busybox's bash doesn't support
		# last_char=${str:(-1)}
		lines=`echo -e -n "$1" | tail -n 1 | wc -l`
		if [ $lines -eq "1" ]; then
			last_is_newline=1
		else
			last_is_newline=0
		fi

		shift
	done
}

function prepare_big_file()
{
	write_log "Create $cp_from(100MiB),\t\twait"
	dd if=/dev/urandom of=$mount_point/$cp_from bs=1M count=100 >& /dev/null
	write_log "\b\b\b\bDONE\n"

	size=$((100*1024*1024));
	filesize=`ls -l $mount_point/$cp_from | awk '{ print $5 }'`

	if [ $filesize -ne $size ]; then
		write_log "write file to hard disk failed, exit...\n"
		exit
	fi

	write_log "Create sha1sum.txt,\t\twait"
	sum=`sha1sum $mount_point/$cp_from | awk '{ print $1 }'`
	write_log "\b\b\b\bDONE\n"

	echo "$sum  $mount_point/$cp_to" > $mount_point/$checksum
}

function prepare()
{
	for sdx in "sda" "sdb" "sdc" "sdd"; do
		removable=`cat /sys/block/$sdx/removable`
		is_usb=`ls -l /sys/block | grep $sdx | grep usb`

		if [ "$removable" == "0" -a -n "$is_usb" ]; then
			break
		fi
	done

	if [ ! -b "/dev/$sdx" ]; then
		write_log "Can't find usbhd device, exit...\n"
		exit
	fi

	write_log "Try mount $sdx to $mount_point,\t\t"
	if [ ! -d $mount_point ]; then
		mkdir $mount_point
	fi

	mounted=`mount | grep $mount_point`
	if [ -n "$mounted" ]; then
		umount $mount_point
	fi

	mount "/dev/$sdx" $mount_point -t ext4 >> /tmp/mount.log 2>&1

	if [ $? -ne 0 ]; then
		write_log "Mount failed, exit...\n"
		mount_log=`cat /tmp/mount.log`
		write_log "$mount_log"
		write_log "\n"
		exit
	fi

	write_log "Successful\n"
	prepare_big_file
}

# ctrl-c handler:
# unmount usbhd and exit
bye=0
function signal_ctrlc()
{
	bye=1
}

prepare
trap signal_ctrlc INT

loops=1
while [ $bye -eq 0 ]; do
	write_log "==> Loop $loops\t\t\t"
	cp $mount_point/$cp_from $mount_point/$cp_to
	sha1sum -c $mount_point/$checksum >& /dev/null

	if [ $? -eq 0 ]; then # successful
		write_log "SUCC\n"
	else
		write_log "FAIL\n"
		break
	fi

	let loops++
done

#exit
umount $mount_point

if [ $bye -eq 1 ]; then
	write_log "USER Press ctrl+c let me quit\n"
else
	write_log "Exit due to last write test failed\n"
fi

exit
